# FUNZIONE: Generazione segnale sinusoidale con diverse armoniche
signal <- function(t, pars, rad = FALSE) {
stopifnot(is.data.frame(pars))
with(pars, {
if (!rad) {
phi <- phi/180*pi
f <- 2*pi*f
}
map_dbl(t, \(t) sum( map_vec(seq_along(w) , \(i) w[i]*sin(t*f[i] + phi[i] ))))
})
}
# Parametri fondamentali
f0 <- 2
fc <- 1000
Tm <- 1
dt <- 1/fc
# Parametri dei segnali
pars_1 <- tibble(
w = c(1, 0.5, 0.3), f = c(f0, 2*f0, 4*f0), phi = c(0, 0, 0))
pars_2 <- tibble(
w = c(1, 0.5, 0.3), f = c(15*f0, 20*f0, 25*f0), phi = c(0, 10, 20))
# Generiamo i segnali ed i loro spettri:
Segnali <- tibble(
t = seq(dt, Tm, dt),
y1 = signal(t, pars_1),
y2 = signal(t, pars_2),
f = 0:(length(t)-1)/max(t),
fft1 = fft(y1),
intensity1 = Mod(fft1) / length(t)*2,
phase1 = Arg(fft1)/pi*180,
fft2 = fft(y2),
intensity2 = Mod(fft2) / length(t)*2,
phase2 = Arg(fft2)/pi*180
)
# Grafico a barre con plot_ly:
pp <- plot_ly() %>%
add_lines(data = Segnali, x = ~f, y = ~intensity1, type = "bar", name = "Segnale 1", marker = list(color= "blue")) %>%
add_lines(data = Segnali, x = ~f, y = ~intensity2, type = "bar", name = "Segnale 2", marker = list(color= "cyan")) %>%
layout(
title = "Spettri dei due Segnali",
xaxis = list(title = "Frequenza [Hz]")
)
ppA marker object has been specified, but markers is not in the mode
Adding markers to the mode...
A marker object has been specified, but markers is not in the mode
Adding markers to the mode...
